package domain;

import enums.City;
import lombok.Data;
import lombok.ToString;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Properties;

/**
 * @author jackcfan
 * @date 2021/9/12
 */
@Data
@ToString
public class User implements BeanNameAware, EnvironmentAware, InitializingBean, SmartInitializingSingleton, DisposableBean {

    private Long id;

    private String name;

    private City city;

    private City[] workCities;

    private List<City> lifeCities;

    private Resource configFileLocation;

    private Company company;

    private Properties context;

    private String contextAsText;

    private String beanName;

    private Environment environment;

    public static User createUser(){
        return new User();
    }

    @Override
    public void setBeanName(String name) {
        System.out.println("User#setBeanName "+name);
        this.beanName = name;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    /**
     * 初始化方法调用顺序
     * 1.@PostConstruct 注解标注的方法
     * 2.afterPropertiesSet() 接口回调
     * 3.xml配置的初始化方法 <bean id="user" class="domain.User" init-method="initMethod">
     * */
    // 单例和原型对象，初始化方法都会调用
    @PostConstruct
    public void init(){
        System.out.println("@PostConstruct init..."+this.beanName);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet init..."+this.beanName);
    }

    public void initMethod(){
        System.out.println("xml initMethod init..."+this.beanName);
    }

    // 初始化完成后回调
    @Override
    public void afterSingletonsInstantiated() {
        System.out.println("afterSingletonsInstantiated ...");
    }

    // 原型对象不会调用销毁方法
    @PreDestroy
    public void PreDestroy(){
        System.out.println("PreDestroy ..."+this.beanName);
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("DisposableBean#destroy ...");
    }

    public void destroyMethod(){
        System.out.println("destroyMethod ...");
    }
}
